package eerbaar.client.internal.ctr;

import eerbaar.client.ctr.IGameController;
import eerbaar.client.ctr.IPersonaCmd;
import eerbaar.game.IGame;
import eerbaar.persona.IPersona;
import eerbaar.position.WrongPositionException;

public class GameController implements IGameController {

    private final IGame game;
    private final IPersona subject;

    public GameController(IPersona subject, IGame game) {
        this.game = game;
        this.subject = subject;
    }

    @Override
    public boolean input(String input) {
        assert (input != null);

        return process(input);
    }

    private boolean process(String input) {
        assert (input != null);

        boolean result = true;

        IPersona persona = this.subject;

        IStimuliHandler handler = StimuliHandlerFactory.get(this.game, persona);

        if (handler == null) {
            return false;
        }

        handler.input(input);

        IPersonaCmd cmd = handler.command(input);
        if (cmd != null) {
            try {
                result = cmd.execute(this.game, persona);
            } catch (WrongPositionException e) {
                // ignore
            }
        }

        return result;
    }

}
